/**
 ----------------------
 1.整张表的增删改查
 2.逻辑复用
 ----------------------
 */
import {useUploadFile} from '@/utils/file/file';
import {configFormConfig} from './form';
import {configTable} from './table';
import {
    deleteConfig,
    fetchConfigById,
    fetchConfigList,
    exportConfig,
    importConfig,
} from '@/api/modules/system/config/config';
import {response} from '@/utils/table/table';
import {setContextMenu} from '@/views/components/contextmenu/data';
import type {SystemConfig} from '@/api/modules/system/config/types';
/**
 * @description: 根据条件获取列表数据
 */
export const configList = async () => {
    try {
            configTable.value.loading = true;
        const {data} = await fetchConfigList(configTable.value.query);
            configTable.value.data = data.rows;
            configTable.value.query.total = data.total;
            configTable.value.loading = false;
    } catch (error) {
            configTable.value.loading = false;
    }
};

/**
 * @description: 根据ID查询数据,并打开表单页面
 * @param {number} id
 */
export const configEdit = async (id?: number) => {
    let targetId: number | string = id ? id : configTable.value.keys[0];
        configTable.value.loading = true;
    const {data} = await fetchConfigById(targetId);
    if (data.data) {
            configFormConfig.value.form = data.data;
            configFormConfig.value.display = true;
    }
        configTable.value.loading = false;
};

/**
 * @description:
 * 清空表单所有内容
 * 打开表单页面
 */
export const configCreate = async () => {
        configFormConfig.value.display = true;
        configFormConfig.value.reset!();
};

export const configDelete = async (id?: number) => {
    let ids = id ? [id] : configTable.value.keys;
    await response(deleteConfig, ids);
    await configList();
        configTable.value.keys = [];
};

// 导出EXCEL文件
export const configExport = () => {
    return exportConfig(configTable.value.query);
};

/**
 * @description:搜索
 * 需要将页码设为第一页，避免翻页后搜不到内容
 */
export const configSearch = () => {
        configTable.value.query.pageNum = 1;
        configList();
};

/**
 * @description: 使用excel导入文件
 */
export const configImport = async () => {
    const files = await useUploadFile({
        accept: '.xls, .xlsx',
    });
    importConfig(files[0]);
};

/**
 * @description:
 *  显示右键菜单
 *  在表格和卡片中复用
 * @param {SystemConfig} item
 */
export const displayConfigMenu = (item: SystemConfig) => {
        configFormConfig.value.form = item;
        configTable.value.keys = [item.configId];
    setContextMenu({
        items: configTable.value.contextmenu,
    });
};
